<?php
namespace app\index\controller;
use app\service\couponService;
use think\Controller;
use think\request;
use think\Db;
class Coupon extends Controller{
    public function couponPc(){
        if (request()->isGet()){
            $coupon_merchant_id = request()->get('coupon_merchant_id');
            //echo $coupon_merchant_id;die;
            $couponMerchantInfo =  Db::name('car_coupon_merchant')
                ->alias('f')
                ->join('parkinglotinfo p','f.parkingNo = p.parkingNo')
                ->field('f.*,p.parkingName')
                ->where('f.id',$coupon_merchant_id)
                ->find();;
            $this->assign('couponMerchantInfo',$couponMerchantInfo);
        }
        if(request()->isPost()){
            $coupon_merchant_id = request()->post('coupon_merchant_id');
            $car_number = request()->post('car_number');
            $couponMerchantInfo =  Db::name('car_coupon_merchant')
                ->alias('f')
                ->join('parkinglotinfo p','f.parkingNo = p.parkingNo')
                ->field('f.*,p.parkingName')
                ->where('f.id',$coupon_merchant_id)
                ->find();;

            //查询车牌是否已经添加
            $carinfo=Db::table("car_coupon")->where("carPlateNo",$car_number)->where("parkingNo",$couponMerchantInfo["parkingNo"])->find();
            if(!empty($carinfo)){
                $r['status'] = '该车牌已经添加';
                return json($r);
            }


            $data["start_time"]=time();
            $data["end_time"]=time()+60*60*24;
            $data["merchant_id"]=$coupon_merchant_id;
            $data["parkingNo"]=$couponMerchantInfo["parkingNo"];
            $data["parkingName"]=$couponMerchantInfo["parkingName"];
            $data["carPlateNo"]=$car_number;
            $data["shops_name"]=$couponMerchantInfo["shops_name"];
            $res=Db::table("car_coupon")->insert($data);
            if($res){
                $r['status'] = '添加成功';

            }else{
                $r['status'] = '添加失败';

            }
            return json($r);
        }
        return $this->fetch("coupon_pc");
    }

    public function couponparkquery(){
        $coupon_id=request()->get("coupon_id");
        $couponParkInfo=Db::table("coupon_park")->where("id",$coupon_id)->find();
        if(empty($couponParkInfo)){
            return "该优惠券不存在";
        }
        if($couponParkInfo["status"]=="2"){
            return "该优惠券无效";
        }
        $parkingNo=$couponParkInfo["parkingNo"];
        $this->assign("coupon_id",$coupon_id);
        $this->assign("parkingNo",$parkingNo);
        return $this->fetch();
    }
    public function couponparkpay(){
        $coupon_id=request()->get("coupon_id");

        $parkingNo=request()->get("parkingNo");

        $carPlateNo=request()->get("car_number");
        //查询客户端是否在线
        $clientinfo=Db::table("client_login")->where("parkingNo",$parkingNo)->where("connect_status","ON")->find();
        if(empty($clientinfo)){
            return "客户端不在线";
        }

        //查询停车入场信息
        $carinfo=Db::table("car_order_in")->where("parkingNo",$parkingNo)->where("carPlateNo",$carPlateNo)->order("id","desc")->limit("1")->find();
        if(empty($carinfo)){
            return $this->fetch("nomsgpre");
        }
        $client=new \swoole_client(SWOOLE_SOCK_TCP);

        if(!$client->Connect("47.106.184.188",9500,0.5)){
            echo "errCode:".$client->errCode."\r\n";
            die("connect failed\r\n");
        }
        $msg='{"bizCode":"Pre1015","parkingNo":"'.$parkingNo.'","clientNo":"'.$clientinfo["clientNo"].'","carPlateNo":"'.$carPlateNo.'","parkingOrderNo":"'.$carinfo["parkingOrderNo"].'","outParkingOrderNo":"'.$carinfo["outParkingOrderNo"].'"}';
        $client->send($msg."\r\n");
        //从服务端接收信息
        $data=$client->recv();

        if(!$data){

            return "查询失败,请稍后再试";
            die("recv failed \r\n");
        }

        $client->close();
        $orderinfo=json_decode($data,true);
        if($orderinfo["bizCode"]=="B1006"){
            if($orderinfo["respCode"]=="00000"){
                return $orderinfo["respMsg"];
            }
        }

        $parkinginfo=Db::table("parkinglotinfo")->where("parkingNo",$orderinfo["parkingNo"])->find();

        $this->assign("parkinginfo",$parkinginfo);
        unset($orderinfo["respMsg"]);
        unset($orderinfo["respCode"]);
        unset($orderinfo["sign"]);
        unset($orderinfo["bizCode"]);
        $orderinfo["parkingName"]=$parkinginfo["parkingName"];

        $orderinfo["payType"]=10;


        //echo "<pre>";
        //var_dump($orderinfo);die;
        $pay_id=Db::name('car_order_query')->insertGetId($orderinfo);
        $this->assign("pay_id",$pay_id);
        $this->assign("coupon_id",$coupon_id);
        $this->assign("orderinfo",$orderinfo);
        return $this->fetch();
    }
    public function couponparkOrder(){
        $pay_id=request()->post("pay_id");
        $coupon_id=request()->post("coupon_id");
        $payinfo=Db::table("car_order_query")->where("id",$pay_id)->find();
        if(empty($payinfo)){
            return json(['info' => "查询账单失败"]);
        }
        $couponparkinfo=Db::table("coupon_park")->where("id",$coupon_id)->find();
        if($couponparkinfo["balance"]<$payinfo["amountRec"]/100){
            return json(['info' => "优惠券余额不足,无法付款"]);
        }

        //执行扣款操作

        Db::startTrans();
        try {

            $parorder=(new couponService())->getOrderPay($payinfo);

            $order_id=Db::table("car_order")->insertGetId($parorder);
            $coupon_park_order["order_id"]=$order_id;
            $coupon_park_order["coupon_park_id"]=$coupon_id;
            $coupon_park_order["parkingNo"]=$parorder["parkingNo"];
            $coupon_park_order["carPlateNo"]=$parorder["carPlateNo"];
            $coupon_park_order["money"]=$payinfo["amountRec"]/100;
            Db::table('coupon_park_order')->insert($coupon_park_order);

            //更新优惠券余额
            Db::table('coupon_park')->where('id', $coupon_id)->setDec('balance', $payinfo["amountRec"]/100);
            // 提交事务
            Db::commit();

            $data["order_id"]=$order_id;
            $this->fsockopen('http://www.aliwgzf.com/index/callback/orderprepaymsg',$data);
            return json(['success' => "缴费成功"]);;
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['info' => $e->getMessage()]);;
        }

    }

    public function ok(){
        return $this->fetch();
    }

    public function fsockopen($url,$post_data=array(),$cookie=array()){
        $url_arr = parse_url($url);
        $port = isset($url_arr['port'])?$url_arr['port']:80;
        if($url_arr['scheme'] == 'https'){
            $url_arr['host'] = 'ssl://'.$url_arr['host'];
        }
        $fp = fsockopen($url_arr['host'],$port,$errno,$errstr,30);
        if(!$fp) return false;
        $getPath = isset($url_arr['path'])?$url_arr['path']:'/index.php';
        $getPath .= isset($url_arr['query'])?'?'.$url_arr['query']:'';
        $method = 'GET';  //默认get方式
        if(!empty($post_data)) $method = 'POST';
        $header = "$method  $getPath  HTTP/1.1\r\n";
        $header .= "Host: ".$url_arr['host']."\r\n";
        if(!empty($cookie)){  //传递cookie信息
            $_cookie = strval(NULL);
            foreach($cookie AS $k=>$v){
                $_cookie .= $k."=".$v.";";
            }
            $cookie_str = "Cookie:".base64_encode($_cookie)."\r\n";
            $header .= $cookie_str;
        }
        if(!empty($post_data)){  //传递post数据
            $_post = array();
            foreach($post_data AS $_k=>$_v){
                $_post[] = $_k."=".urlencode($_v);
            }
            $_post = implode('&', $_post);
            $post_str = "Content-Type:application/x-www-form-urlencoded; charset=UTF-8\r\n";
            $post_str .= "Content-Length: ".strlen($_post)."\r\n";  //数据长度
            $post_str .= "Connection:Close\r\n\r\n";
            $post_str .= $_post;  //传递post数据
            $header .= $post_str;
        }else{
            $header .= "Connection:Close\r\n\r\n";
        }
        fwrite($fp, $header);
        //echo fread($fp,1024);
        usleep(1000); // 这一句也是关键，如果没有这延时，可能在nginx服务器上就无法执行成功
        fclose($fp);
        return true;
    }
}